<?php
/**
 * Created by User: wene<china_wangyu@aliyun.com> Date: 2019/4/11 Time: 15:29
 */

namespace think\restful\validate;


use think\restful\Base;
use think\restful\exception\ApiException;

/**
 * Class Host 验证域名或者IP
 * @package think\restful\validate
 */
class Host extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 执行host验证（采取ping方式）
     * @param string $host
     * @return bool|null
     */
    public function execute(string $host = ''):?bool
    {
        $apiHostDomain = str_replace(['http://', 'https://'], '', strtolower($host));
        if (strstr($apiHostDomain, ':')) $apiHostDomain = explode(':', $apiHostDomain)[0];
        if (strstr($apiHostDomain, '/')) $apiHostDomain = explode('/', $apiHostDomain)[0];
        if ($this->rule($apiHostDomain)=== false) ApiException::exception('参数错误：host不是有效的域名或者IP');
        return true;
    }

    /**
     * 是否为有效的域名或者IP
     * @param string $apiHostDomain
     * @return bool
     */
    private function rule(string $apiHostDomain = ''):bool
    {
        $status = -1;
        if (strcasecmp(PHP_OS, 'WINNT') === 0) {
            // Windows 服务器下
            exec("ping -n 1 {$apiHostDomain}", $outcome, $status);
        } elseif (strcasecmp(PHP_OS, 'Linux') === 0) {
            // Linux 服务器下
            exec("ping -c 1 {$apiHostDomain}", $outcome, $status);
        }
        return $status !== 0 ? false : true;
    }
}